package com.authine.cloudpivot.ext.service.impl;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.service.TokenService;
import com.authine.cloudpivot.web.api.exception.PortalException;
import org.apache.axis.utils.StringUtils;
import org.apache.commons.collections4.MapUtils;
import org.redisson.Redisson;
import org.redisson.RedissonMap;
import org.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Author hxd
 * @Date 2022/8/15 12:47
 * @Description 获取浩通门户系统token
 **/
@Service
public class TokenServceImpl implements TokenService {
    @Value("${other.portal.client_id:0b908d35ff8ef2c13857d61f9d13e9d8o14s3BeL5Z4}")
    String client_id ;
    @Value("${other.portal.client_secet:g5oeY859DEl3mlDunZy50DB0UAjx9CdHmzAKGhvJ6F}")
    String client_secet;
    @Value("${other.portal.scope:read}")
    String scope = "read";
    @Value("${other.portal.grant_type:client_credentials}")
    String grant_type  ;
    @Value("${other.portal.authUrl:http://120.27.239.190/oauth/token}")
    String authUrl ;


    @Autowired
    Redisson redisson;
    @Autowired
    RestTemplate restTemplate;


    public String getAuthorization(){
        RMap<Object, Object> mapToken = redisson.getMap("portal.token");
        long expires = MapUtils.getLong(mapToken,"expires", 0L);
        if (System.currentTimeMillis() > expires){
            //token 过期,刷新token
            mapToken.putAll(initToken());
        }

        return MapUtils.getString(mapToken,"authorization","");
    }


    public Map<String,Object> initToken() {



        String param = String.format("grant_type=%s&scope=%s&client_id=%s&client_secet=%s", grant_type, scope, client_id, client_secet);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> request = new HttpEntity<>(param, headers);

        Map<String,Object> obj = restTemplate.postForObject(authUrl,request,Map.class);

        long expires_in = MapUtils.getLong(obj, "expires_in", 0L);
        if (expires_in==0){
            throw  new PortalException(-1L,"token 获取失败, error:".concat(JSON.toJSONString(obj)));
        }
        String access_token = MapUtils.getString(obj, "access_token", "");
        if (StringUtils.isEmpty(access_token)) {
            throw  new PortalException(-1L,"token 获取失败,  error:".concat(JSON.toJSONString(obj)));
        }
        String token_type = MapUtils.getString(obj, "token_type", "");

        obj.put("expires",System.currentTimeMillis()+(expires_in*1000));
        obj.put("authorization",token_type.concat(" ").concat(access_token));


        return obj;
    }
}
